<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  useMessage,
  NButton, NForm, NFormItem, NInput, NInputNumber, NPopconfirm, NTreeSelect, NTag, NSwitch, NFlex,
  NAvatar, NSelect, NImage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'

import {getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '优惠券设置' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '优惠券设置',
  initForm: { order: 0 },
  doCreate: api.createCouponsRule,
  doUpdate: api.updateCouponsRule,
  doDelete: api.deleteCouponsRule,
  refresh: () => $table.value?.handlerefresh(),
})

const deptOption = ref([])
const isDisabled = ref(false)

const data = reactive({
  uploadAction: base_path + 'api/marketing/coupons_rule/file',
  token: getToken(),
});

onMounted(() => {
  $table.value?.handleSearch()
  // api.getCategory().then((res) => (deptOption.value = res.data))
  api.getCategoryTree().then((res) => (deptOption.value = res.data))
})

const deptRules = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '优惠券名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '封面',
    key: 'cover',
    width:100,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {},
          [h(NAvatar, {
            src: row.cover,
            size: "small",
          })]
      )

    },
  },
    {
    title: '面额',
    key: 'value',
    align: 'center',
    width: 100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.value }
      )
    },
  },

    {
    title: '使用起点',
    key: 'role',
    align: 'center',
    width: 100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.role }
      )
    },
  },
    {
    title: '过期天数',
    key: 'expire_at',
    align: 'center',
    width: 100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.expire_at }
      )
    },
  },
    {
    title: '备注',
    key: 'remark',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
    {
    title: '禁用',
    key: 'state',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.state,
        loading: !!row.publishing,
        checkedValue: false,
        uncheckedValue: true,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                console.log('row', row.parent_id)
                // if (row.parent_id === 0) {
                //   isDisabled.value = true
                // } else {
                //   isDisabled.value = false
                // }
                handleEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/category/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/category/delete']]
              ),
            default: () => h('div', {}, '确定删除该优惠券吗?'),
          }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    await api.updateCouponsRule(row)
    $message?.success(row.state ? '已取消禁' : '已禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false ? true : false
  } finally {
    row.publishing = false
  }
}

//封面图
const message = useMessage();
const customRequestMethod1 = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        if (data.code === 200) {
          modalForm.value.cover = data.data.url
          message.success('缩略图上传成功');
          options.onProgress(data);
        } else {
          message.error(data.msg);
        }
      })
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="优惠券设置">
    <template #action>
      <div>
        <NButton
          v-permission="'post/api/content/category/create'"
          class="float-right mr-15"
          type="primary"
          @click="addDepts"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建优惠券
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="api.getCouponsRule"
    >
      <template #queryBar>
        <QueryBarItem label="优惠券名称" :label-width="80">
          <NInput
            v-model:value="queryItems.name"
            clearable
            type="text"
            placeholder="请输入名称"
            @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      @save="handleSave"
    >
      <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :rules="deptRules"
      >

        <NFormItem label="名称" path="name">
          <NInput v-model:value="modalForm.name" clearable placeholder="请输入名称" />
        </NFormItem>
        <NFormItem label="奖品图片" path="cover" style="width:100%">
          <NImage v-if="modalForm.cover" width="60" style="border-radius: 5px;margin-right: 15px;"
                  :src="modalForm.cover"></NImage>
          <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                   :show-file-list=false :custom-request="customRequestMethod1" list-type="image">
            <NButton>上传</NButton>
          </NUpload>
        </NFormItem>
        <NFormItem label="面额" path="value">
          <NInputNumber v-model:value="modalForm.value" :default-value="0" placeholder="请输入数量" min="0"/>
        </NFormItem>
        <NFormItem label="使用起点" path="role">
          <NInputNumber v-model:value="modalForm.role" :default-value="0" placeholder="请输入使用起点" min="0"></NInputNumber>
        </NFormItem>
        <NFormItem label="过期天数" path="expire_at">
          <NInputNumber v-model:value="modalForm.expire_at" :default-value="1"  placeholder="请输入天数" min="1"/>
        </NFormItem>
        <NFormItem label="备注" path="remark">
          <NInput v-model:value="modalForm.remark" type="textarea" clearable />
        </NFormItem>

      </NForm>
    </CrudModal>
  </CommonPage>
</template>
